﻿using Microsoft.AspNetCore.Mvc;
using ERP.EquipmentManage;
using ERP.EquipmentManage.Dtos;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ERP.Web.Controllers
{
    /// <summary>
    /// 设备管理控制器
    /// </summary>
    public class EquipmentController : Controller
    {
        private readonly IEquipmentMaintenancePlanService _planService;
        private readonly IDvsubjectService _dvsubjectService;
        private readonly IPlanDvsubjectService _planDvsubjectService;
        private readonly ILogger<EquipmentController> _logger;

        public EquipmentController(
            IEquipmentMaintenancePlanService planService,
            IDvsubjectService dvsubjectService,
            IPlanDvsubjectService planDvsubjectService,
            ILogger<EquipmentController> logger)
        {
            _planService = planService;
            _dvsubjectService = dvsubjectService;
            _planDvsubjectService = planDvsubjectService;
            _logger = logger;
        }

        /// <summary>
        /// 设备维护计划首页
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取设备维护计划列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetMaintenancePlanList(GetEquipmentMaintenancePlanInputDto input, int page = 1, int limit = 10)
        {
            try
            {
                // 转换Layui分页参数为ABP分页参数
                input.SkipCount = (page - 1) * limit;
                input.MaxResultCount = limit;
                
                var result = await _planService.GetListAsync(input);
                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取设备维护计划列表失败");
                return Json(new
                {
                    code = 1,
                    msg = ex.Message,
                    count = 0,
                    data = new List<object>()
                });
            }
        }

        /// <summary>
        /// 根据ID获取设备维护计划
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaintenancePlan(int id)
        {
            try
            {
                var result = await _planService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取设备维护计划失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建设备维护计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateMaintenancePlan([FromBody] CreateEquipmentMaintenancePlanDto input)
        {
            try
            {
                var result = await _planService.CreateAsync(input);
                return Json(new { success = true, data = result, message = "创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建设备维护计划失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新设备维护计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateMaintenancePlan([FromBody] JsonElement requestData)
        {
            try
            {
                _logger.LogInformation("接收到更新请求数据: {Data}", requestData.ToString());
                
                // 尝试以不区分大小写的方式获取ID
                int id = 0;
                bool idFound = false;
                
                // 尝试直接从请求中获取id字段
                if (requestData.TryGetProperty("id", out JsonElement idElement) && idElement.ValueKind == JsonValueKind.Number && idElement.TryGetInt32(out id))
                {
                    _logger.LogInformation("成功获取id(小写): {Id}", id);
                    idFound = true;
                }
                // 尝试获取大写的Id字段
                else if (requestData.TryGetProperty("Id", out idElement) && idElement.ValueKind == JsonValueKind.Number && idElement.TryGetInt32(out id))
                {
                    _logger.LogInformation("成功获取Id(大写): {Id}", id);
                    idFound = true;
                }
                // 尝试从input对象中获取id
                else if (requestData.TryGetProperty("input", out JsonElement inputElement))
                {
                    if (inputElement.TryGetProperty("id", out idElement) && idElement.ValueKind == JsonValueKind.Number && idElement.TryGetInt32(out id))
                    {
                        _logger.LogInformation("从input对象中获取id(小写): {Id}", id);
                        idFound = true;
                    }
                    else if (inputElement.TryGetProperty("Id", out idElement) && idElement.ValueKind == JsonValueKind.Number && idElement.TryGetInt32(out id))
                    {
                        _logger.LogInformation("从input对象中获取Id(大写): {Id}", id);
                        idFound = true;
                    }
                }
                
                if (!idFound || id <= 0)
                {
                    _logger.LogError("无法获取有效的ID字段，ID: {Id}", id);
                    return Json(new { success = false, message = "无法获取有效的ID字段，请确保请求包含有效的数字类型id且值大于0" });
                }
                
                // 尝试获取input对象
                UpdateEquipmentMaintenancePlanDto input;
                if (requestData.TryGetProperty("input", out JsonElement inputElement2))
                {
                    try
                    {
                        input = JsonSerializer.Deserialize<UpdateEquipmentMaintenancePlanDto>(
                            inputElement2.GetRawText(),
                            new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
                        );
                        _logger.LogInformation("成功转换input对象");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "无法转换input对象");
                        return Json(new { success = false, message = "无法解析input数据: " + ex.Message });
                    }
                }
                else
                {
                    // 尝试直接使用requestData作为DTO
                    try
                    {
                        input = JsonSerializer.Deserialize<UpdateEquipmentMaintenancePlanDto>(
                            requestData.GetRawText(),
                            new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
                        );
                        _logger.LogInformation("成功将整个请求转换为DTO");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "无法将请求转换为DTO: {Error}", ex.Message);
                        _logger.LogError("请求数据: {Data}", requestData.ToString());
                        return Json(new { success = false, message = "无法解析更新数据: " + ex.Message });
                    }
                }
                
                // 验证DTO中的必填字段
                if (input == null)
                {
                    _logger.LogError("解析后的DTO为null");
                    return Json(new { success = false, message = "无法解析请求数据" });
                }
                
                if (string.IsNullOrWhiteSpace(input.PlanCode))
                {
                    _logger.LogError("计划编码为空");
                    return Json(new { success = false, message = "计划编码不能为空" });
                }
                
                if (string.IsNullOrWhiteSpace(input.PlanName))
                {
                    _logger.LogError("计划名称为空");
                    return Json(new { success = false, message = "计划名称不能为空" });
                }
                
                var result = await _planService.UpdateAsync(id, input);
                return Json(new { success = true, data = result, message = "更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新设备维护计划失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除设备维护计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteMaintenancePlan(int id)
        {
            try
            {
                await _planService.DeleteAsync(id);
                return Json(new { success = true, message = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除设备维护计划失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除设备维护计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchDeleteMaintenancePlan([FromBody] List<int> ids)
        {
            try
            {
                await _planService.BatchDeleteAsync(ids);
                return Json(new { success = true, message = "批量删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除设备维护计划失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 检查计划编码是否存在
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> CheckPlanCodeExists(string planCode, int? excludeId = null)
        {
            try
            {
                var exists = await _planService.CheckPlanCodeExistsAsync(planCode, excludeId);
                return Json(new { exists = exists });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查计划编码是否存在失败");
                return Json(new { exists = false });
            }
        }

        /// <summary>
        /// 获取设备检查项目列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetDvsubjectList(GetDvsubjectInputDto input, int page = 1, int limit = 10)
        {
            try
            {
                // 转换Layui分页参数
                input.PageIndex = page;
                input.PageSize = limit;
                
                var result = await _dvsubjectService.GetPagedListAsync(input);
                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取设备检查项目列表失败");
                return Json(new
                {
                    code = 1,
                    msg = ex.Message,
                    count = 0,
                    data = new List<object>()
                });
            }
        }

        /// <summary>
        /// 获取计划相关的设备点检项目列表（已添加到当前计划的项目）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetPlanDvsubjectList(string planCode, int page = 1, int limit = 10)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(planCode))
                {
                    // 如果没有计划编码，返回空列表
                    return Json(new
                    {
                        code = 0,
                        msg = "success",
                        count = 0,
                        data = new List<object>()
                    });
                }

                var items = await _planDvsubjectService.GetPlanDvsubjectsAsync(planCode);
                
                // 简单分页处理
                var pagedItems = items.Skip((page - 1) * limit).Take(limit).ToList();

                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = items.Count,
                    data = pagedItems
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取计划设备检查项目列表失败");
                return Json(new
                {
                    code = 1,
                    msg = ex.Message,
                    count = 0,
                    data = new List<object>()
                });
            }
        }

        /// <summary>
        /// 删除设备点检保养项目
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteDvsubject([FromBody] DeleteDvsubjectRequestDto request)
        {
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    return Json(new { success = false, message = "请选择要删除的项目" });
                }

                if (request.Ids.Count == 1)
                {
                    // 单个删除
                    await _dvsubjectService.DeleteAsync(request.Ids[0]);
                }
                else
                {
                    // 批量删除
                    await _dvsubjectService.BatchDeleteAsync(request.Ids);
                }

                return Json(new 
                { 
                    success = true, 
                    message = request.Ids.Count == 1 ? "删除成功" : $"批量删除成功，共删除 {request.Ids.Count} 项"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除设备点检保养项目失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取可选择的设备点检项目列表（用于弹出对话框选择）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetAvailableDvsubjectList(GetDvsubjectInputDto input, int page = 1, int limit = 10)
        {
            try
            {
                // 转换Layui分页参数
                input.PageIndex = page;
                input.PageSize = limit;
                
                var result = await _dvsubjectService.GetPagedListAsync(input);
                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取可选择设备检查项目列表失败");
                return Json(new
                {
                    code = 1,
                    msg = ex.Message,
                    count = 0,
                    data = new List<object>()
                });
            }
        }

        /// <summary>
        /// 添加设备点检项目到维护计划
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddDvsubjectToPlan([FromBody] AddDvsubjectToPlanRequestDto request)
        {
            try
            {
                // 这里应该调用维护计划服务来添加项目关联
                // 由于当前只是演示，我们返回成功响应
                // 实际项目中需要在维护计划和点检项目之间建立关联关系
                
                _logger.LogInformation("添加项目到维护计划: PlanId={PlanId}, DvsubjectId={DvsubjectId}", 
                    request.PlanId, request.DvsubjectId);
                
                return Json(new { success = true, message = "添加项目成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加设备点检项目到维护计划失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 保存计划的设备点检项目列表
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SavePlanDvsubjects(string planCode, string dvsubjectIdsJson)
        {
            try
            {
                _logger.LogInformation("接收到保存计划项目请求");
                _logger.LogInformation("计划编码: {PlanCode}", planCode);
                _logger.LogInformation("项目ID JSON: {DvsubjectIdsJson}", dvsubjectIdsJson);
                
                if (string.IsNullOrWhiteSpace(planCode))
                {
                    _logger.LogWarning("计划编码为空");
                    return Json(new { success = false, message = "计划编码不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dvsubjectIdsJson))
                {
                    _logger.LogWarning("设备点检项目ID JSON为空");
                    return Json(new { success = false, message = "设备点检项目ID列表不能为空" });
                }

                // 手动解析JSON
                List<int> dvsubjectIds;
                try
                {
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        AllowTrailingCommas = true,
                        ReadCommentHandling = JsonCommentHandling.Skip
                    };
                    dvsubjectIds = JsonSerializer.Deserialize<List<int>>(dvsubjectIdsJson, options);
                    
                    // 验证解析后的列表
                    if (dvsubjectIds == null)
                    {
                        _logger.LogError("解析后的项目ID列表为null");
                        return Json(new { success = false, message = "无法解析项目ID列表" });
                    }
                    
                    // 过滤无效的ID
                    var validIds = dvsubjectIds.Where(id => id > 0).ToList();
                    if (validIds.Count != dvsubjectIds.Count)
                    {
                        _logger.LogWarning("项目ID列表包含无效ID，已过滤。原始数量: {Original}, 有效数量: {Valid}", 
                            dvsubjectIds.Count, validIds.Count);
                        dvsubjectIds = validIds;
                    }
                    
                    _logger.LogInformation("解析后的项目ID列表: {@DvsubjectIds}", dvsubjectIds);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "解析项目ID JSON失败: {Json}", dvsubjectIdsJson);
                    _logger.LogError("异常详情: {Message}", ex.Message);
                    return Json(new { success = false, message = "项目ID数据格式错误: " + ex.Message });
                }
                
                if (dvsubjectIds.Count == 0)
                {
                    _logger.LogWarning("项目ID列表为空");
                    return Json(new { success = true, message = "没有项目需要保存" });
                }

                _logger.LogInformation("开始保存: 计划编码={PlanCode}, 项目数量={Count}", planCode, dvsubjectIds.Count);
                
                foreach (var id in dvsubjectIds)
                {
                    _logger.LogInformation("项目ID: {DvsubjectId}, 类型: {Type}", id, id.GetType().Name);
                }

                try
                {
                    await _planDvsubjectService.SavePlanDvsubjectsAsync(planCode, dvsubjectIds);
                    _logger.LogInformation("保存成功");
                    return Json(new { success = true, message = "保存成功" });
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "调用服务保存项目列表失败");
                    _logger.LogError("异常详情: {Message}", ex.Message);
                    return Json(new { success = false, message = "保存失败: " + ex.Message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存计划设备检查项目列表失败");
                _logger.LogError("异常详情: {Message}", ex.Message);
                _logger.LogError("堆栈跟踪: {StackTrace}", ex.StackTrace);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 设备维护计划新增编辑页面
        /// </summary>
        public async Task<IActionResult> AddEdit(int? id)
        {
            if (id.HasValue)
            {
                try
                {
                    var plan = await _planService.GetAsync(id.Value);
                    return View(plan);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取设备维护计划失败，ID: {Id}", id);
                    return View();
                }
            }
            return View();
        }

        /// <summary>
        /// 测试数据库连接和数据获取
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> TestData()
        {
            try
            {
                var input = new GetEquipmentMaintenancePlanInputDto
                {
                    SkipCount = 0,
                    MaxResultCount = 10
                };
                
                var result = await _planService.GetListAsync(input);
                return Json(new { 
                    success = true, 
                    totalCount = result.TotalCount,
                    itemCount = result.Items.Count,
                    items = result.Items,
                    message = "数据获取成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new { 
                    success = false, 
                    message = ex.Message,
                    stackTrace = ex.StackTrace
                });
            }
        }
    }
}
